package com.alogic.es.xscript.search;

import com.alogic.xscript.AbstractLogiclet;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.lang3.StringUtils;

/**
 * query by script
 *
 * @since 1.6.13.9 [20200824 duanyy]
 */
public class EsScript extends AbstractLogiclet {
    protected String $source;
    protected String $lang = "painless";

    public EsScript(String tag, Logiclet p) {
        super(tag, p);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);
        $source = PropertiesConstants.getRaw(p,"source",$source);
        $lang = PropertiesConstants.getRaw(p,"lang", $lang);
    }

    protected void onExecute(XsObject root, XsObject current, LogicletContext ctx, ExecuteWatcher watcher) {
        String source = PropertiesConstants.transform(ctx,$source,"");
        if (StringUtils.isNotEmpty(source)) {
            XsObject query = current.getObjectChild("script", true);
            XsObject f = query.getObjectChild("script",true);
            f.addProperty("source",source);
            f.addProperty("lang", PropertiesConstants.transform(ctx,$lang,"painless"));
        }
    }
}